<?php
namespace app\merchant\controller;
use app\common\controller\TestBase;
use app\common\model\CardGeneral;
use app\common\model\CardGoods;
use app\common\model\CardGoodsCate;
use app\common\model\CardMember;
use app\common\model\CardOrder;
use app\common\model\CardStore;
use app\common\model\CardUserGet;
use app\common\model\CardUserUpdate;
use app\common\model\Agent;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\System;
use app\common\controller\AdminBase;
use think\Controller;
use think\Session;
use Wechat\Wxobjopen;
class Shoptest extends TestBase
{
    //首页
    public function shopmall(){
        $card_id = $this->get_cardus_id();
        $CardOrder = new CardOrder();
        $CardGoods = new CardGoods();
        $sume['order'] = $CardOrder->where('card_id',$card_id)->count();
        $sume['goods'] = $CardGoods->where('card_id',$card_id)->count();
        //搜素
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['goods_name'] != ''){
                $map['goods_name'] = array('like', '%' . trim($p_data['goods_name']) . '%');
            }else{
                $p_data['goods_name'] = '';
            }
            if ($p_data['statu'] != ''){
                $map['statu'] = $p_data['statu'];
            }else{
                $p_data['statu'] = '';
            }

            if (!empty($p_data['search_date'])) {
                $date = explode(" - ", $p_data['search_date']);
                $starttime = strtotime($date[0]);
                $endtime = strtotime($date[1]);
            } else {
                $starttime = 0;
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
        } else {
            $p_data['statu'] = '';
            $p_data['goods_name'] = '';
            $p_data['starttime'] = '';
            $p_data['endtime'] = '';
            $starttime = 0;
            $endtime = strtotime(date('Y-m-d H:i:s'));
        }
        $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        $map['card_id'] = $card_id;
        $orderlist = $CardOrder->where($map)->order('id desc')->paginate('10', false, ['query' => request()->param()]);
        $card['card_id'] = $card_id;
        $this->assign('card',$card);
        $this->assign('p_data',$p_data);
        $this->assign('sume',$sume);
        $this->assign('orderlist',$orderlist);
        return $this->fetch();
    }

    //商品列表
    public function goodslist($card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardGoods = new CardGoods();
        //搜素
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['goods_name'] != ''){
                $map['a.goods_name'] = array('like', '%' . trim($p_data['goods_name']) . '%');
            }else{
                $p_data['goods_name'] = '';
            }
            if ($p_data['statu'] != ''){
                $map['a.statu'] = $p_data['statu'];
            }else{
                $p_data['statu'] = '';
            }
            if ($p_data['goods_type'] != ''){
                $map['a.goods_type'] = $p_data['goods_type'];
            }else{
                $p_data['goods_type'] = '';
            }
            if (!empty($p_data['search_date'])) {
                $date = explode(" - ", $p_data['search_date']);
                $starttime = strtotime($date[0]);
                $endtime = strtotime($date[1]);
            } else {
                $starttime = 0;
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
        } else {
            $p_data['statu'] = '';
            $p_data['goods_name'] = '';
            $p_data['goods_type'] = '';
            $p_data['starttime'] = '';
            $p_data['endtime'] = '';
            $starttime = 0;
            $endtime = strtotime(date('Y-m-d H:i:s'));
        }
        $map['a.statu'] = ['neq',2];
        $map['a.card_id'] = $card_id;
        $map['a.create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        $list = $CardGoods->alias('a')
            ->join('wn_card_goods_cate b', 'a.cate_id=b.id', 'left')
            ->where($map)->order('id desc')
            ->field('a.id,a.goods_name,a.card_id,a.statu,a.goods_type,a.goods_card_id,a.img_url,a.goods_price,a.stock,a.goods_img,a.create_time,b.name as cate_name')
            ->paginate('10', false, ['query' => request()->param()]);
        $card['card_id'] = $card_id;
        $this->assign('p_data',$p_data);
        $this->assign('card',$card);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //商品详情
    public function goodsinfo($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardGoods = new CardGoods();
        $info = $CardGoods->where(array('id'=>$id))->find();
        $card['card_id'] = $card_id;
        $this->assign('card',$card);
        $this->assign('goods', $info);
        return $this->fetch();
    }

    //添加商品
    public function goodsadd($card_id = ''){
        $card_id = $this->get_cardus_id();
        if (Request()->isPost()){
            $arr = request()->post();
            $data = $arr;
            $CardGeneral = new CardGeneral();
            $data['goods_name'] = $arr['goods_name'];
            $data['show'] = $arr['show'];
            $data['card_id'] = $card_id;
            $data['zs_money'] = $arr['zs_money'];
            $data['goods_type'] = $arr['goods_type'];
            $data['goods_price'] = $arr['goods_price'];
            $data['goods_card_id'] = $arr['card_id'];
            if ($arr['goods_type'] == 'card_dis'){
                $card_info = $CardGeneral->where('card_id',$arr['card_id'])->find();
                $data['goods_color'] = getcolor(cardgetinfo($arr['card_id'],1,3));
                $data['goods_img'] = $card_info['logo_url'];
            }
            if ($arr['goods_type'] == 'red_money'){
                $data['goods_color'] = '#B52631';
                $data['goods_img'] = '/static/images/257.png';
            }

            $date = explode(" - ", $arr['search_date']);
            $data['begin_time']=strtotime($date[0]);
            $data['end_time']=strtotime($date[1]);
            $data['create_time'] = time();
            $CardGoods = new CardGoods();
            $res = $CardGoods->allowField(true)->save($data);
            if ($res == false){
                $this->error("添加失败",url('shop/goodslist',['card_id'=>$card_id])) ;
            }else{
                $this->success("添加成功",url('shop/goodslist',['card_id'=>$card_id]));
            }
        }else{
            $card['card_id'] = $card_id;
            $CardGoodsCate = new CardGoodsCate();
            $catelist = $CardGoodsCate->where($card)->select();
            $this->assign('catelist',$catelist);
            $this->assign('card',$card);
            return $this->fetch();
        }
    }

    //修改商品
    public function goodsedit($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        if (Request()->isPost()){
            $arr = request()->post();
            $data = $arr;
            $data['show'] = $arr['show'];
            $data['card_id'] = $card_id;
            if (isset($arr['zs_money'])) {
                $data['zs_money'] = $arr['zs_money'];
            }
            $data['goods_price'] = $arr['goods_price'];
//            $data['begin_time']=strtotime($arr['begin_time']);
//            $data['end_time']=strtotime($arr['end_time']);
            $data['create_time'] = time();
            $date = explode(" - ", $arr['search_date']);
            $data['begin_time']=strtotime($date[0]);
            $data['end_time']=strtotime($date[1]);
            $CardGoods = new CardGoods();
            $res = $CardGoods->allowField(true)->save($data,['id'=>$id]);
            if ($res == false){
                $this->error("修改失败",url('shop/goodslist',['card_id'=>$card_id])) ;
            }else{
                $this->success("修改成功",url('shop/goodslist',['card_id'=>$card_id])) ;
            }
        }else{
            $CardGoods = new CardGoods();
            $info = $CardGoods->where(array('id'=>$id))->find();
            $card['card_id'] = $card_id;
            $CardGoodsCate = new CardGoodsCate();
            $catelist = $CardGoodsCate->where($card)->select();
            $this->assign('catelist',$catelist);
            $this->assign('card',$card);
            $this->assign('info',$info);
            return $this->fetch();
        }
    }

    //删除商品
    public function goodsdel($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardGoods = new CardGoods();
        $data['statu'] = 2;
        $del = $CardGoods->save($data,['id'=>$id]);
        if ($del) {
            $this->success('删除成功',url('shop/goodslist',['card_id'=>$card_id]));
        } else {
            $this->error('删除失败',url('shop/goodslist',['card_id'=>$card_id]));
        }
    }

    //下架商品
    public function goodsoff($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardGoods = new CardGoods();
        $statu = $CardGoods->where('id',$id)->value('statu');
        $data['statu'] = $statu == 1 ? 0:1;
        $mesg = $data['statu']  == 1 ? '下架' : '上架';
        $res = $CardGoods->save($data,['id'=>$id]);
        if ($res) {
            $this->success($mesg.'成功',url('shop/goodslist',['card_id'=>$card_id]));
        } else {
            $this->error($mesg.'失败',url('shop/goodslist',['card_id'=>$card_id]));
        }
    }

    //订单
    public function orderconf($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $map['id'] = $id;
        $CardGoods = new CardGoods();
        $list = $CardGoods->where($map)->order('id desc')->select();
        $this->assign('list', $list);
        $card['card_id'] = $card_id;
        $this->assign('card',$card);
        return $this->fetch();
    }

    //订单列表
    public function orderlist($card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardOrder = new CardOrder();
        //搜素
        $request = request();
        $p_data = $request->get();
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['goods_name'] != ''){
                $map['goods_name'] = array('like', '%' . trim($p_data['goods_name']) . '%');
            }else{
                $p_data['goods_name'] = '';
            }
            if ($p_data['statu'] != ''){
                $map['statu'] = $p_data['statu'];
            }else{
                $p_data['statu'] = '';
            }
            if (!empty($p_data['search_date'])) {
                $date = explode(" - ", $p_data['search_date']);
                $starttime = strtotime($date[0]);
                $endtime = strtotime($date[1]);
            } else {
                $starttime = 0;
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
        } else {
            $p_data['statu'] = '';
            $p_data['goods_name'] = '';
            $p_data['starttime'] = '';
            $p_data['endtime'] = '';
            $starttime = 0;
            $endtime = strtotime(date('Y-m-d H:i:s'));
        }
        $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        $map['card_id'] = $card_id;
        $list = $CardOrder->where($map)->order('id desc')->paginate('20', false, ['query' => request()->param()]);
        $listoff = $CardOrder->where(array('card_id'=>$card_id,'statu'=>2))->order('id desc')->select();
        $card['card_id'] = $card_id;
        $this->assign('list', $list);
        $this->assign('p_data',$p_data);
        $this->assign('listoff', $listoff);
        $this->assign('card',$card);
        return $this->fetch();
    }

    //订单详情
    public function orderinfo($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardOrder = new CardOrder();
        $CardGoods = new CardGoods();
        $CardUserGet = new CardUserGet();
        $order = $CardOrder->where(array('id'=>$id))->find();
        $goods = $CardGoods->where(array('id'=>$order['gid']))->find();
        $user = $CardUserGet->where(['id'=>$order['openid']])->find();
        $card['card_id'] = $card_id;
        $this->assign('card',$card);
        $this->assign('order', $order);
        $this->assign('goods', $goods);
        $this->assign('user', $user);
        return $this->fetch();
    }

    //修改订单
    public function orderedit($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        if (Request()->isPost()){
            $arr = request()->post();
            $data = [
                'address'=>$arr['address'],
                'price'=>$arr['price'],
                'number'=>$arr['number'],
                'create_time'=>time(),
            ];
            $CardOrder = new CardOrder();
            $res = $CardOrder->save($data,['id'=>$id]);
            if ($res !== false){
                $this->success('修改成功',url('shop/orderlist',['card_id'=>$card_id]));
            }else{
                $this->error('修改失败',url('shop/orderlist',['card_id'=>$card_id]));
            }
        }else{
            $CardOrder = new CardOrder();
            $info = $CardOrder->where(array('id'=>$id))->find();
            $card['card_id'] = $card_id;
            $this->assign('card',$card);
            $this->assign('info', $info);
            return $this->fetch();
        }
    }

    //关闭订单
    public function orderoff($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $data['statu'] = 1;
        $CardOrder = new CardOrder();
        $CardGoods = new CardGoods();
        $CardUserGet = new CardUserGet();
        $del = $CardOrder->where(array('id'=>$id))->update($data);
        $order = $CardOrder->where(array('id'=>$id))->find();
        $card = $CardUserGet->where(['id'=>$order['uid']])->find();
        $goods = $CardGoods->where(['id'=>$order['gid']])->value('goods_name');
        if ($del) {
            $bonus = [
                'card_id'=>$card['card_id'],
                'code'=>$card['code'],
                'price'=>$order['price'],
                'name'=>$goods,
                'openid'=>$card['openid'],
                'mid'=>$card['mid'],
            ];
            $res = $this->updatebonus($bonus);
            if ($res == 0){
                $this->success('关闭成功',url('shop/orderlist',['card_id'=>$card_id]));
            }else{
                $this->error('关闭失败',url('shop/orderlist',['card_id'=>$card_id]));
            }
        } else {
            $this->error('关闭失败',url('shop/orderlist',['card_id'=>$card_id]));
        }
    }

    //删除订单
    public function orderdel($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardOrder = new CardOrder();
        $del = $CardOrder->where(['id'=>$id])->delete();
        if ($del) {
            $this->success('删除成功',url('shop/orderlist',['card_id'=>$card_id]));
        } else {
            $this->error('删除失败',url('shop/orderlist',['card_id'=>$card_id]));
        }
    }

    //更新卡券数据
    public function updatebonus($arr){
        $data = array(
            'card_id'=>$arr['card_id'],
            'code'=> $arr['code'],
            'add_bonus'=>$arr['price'],
            'record_bonus'=>'积分兑换:'.$arr['name'].'订单关闭退分',
            "notify_optional"=>array(
                "is_notify_bonus"=>true,
                "is_notify_balance"=> true,
                "is_notify_custom_field1"=>true
            )
        );
        $options = $this->options($arr['card_id']);
        $weObj = new Wxobjopen($options);
        $res = $weObj->updateUserInfo($data);
        if ($res['errcode'] == 0){
            $bonus['add_bonus']=abs($data['add_bonus']);
            $bonus['record_bonus'] = '积分兑换:'.$arr['name'].'订单关闭退分';
            $bonus['openid']=$arr['openid'];
            $bonus['card_id']=$arr['card_id'];
            $bonus['code']=$arr['code'];
            $bonus['create_time'] = time();
            $bonus['outerstr'] = 'BONUSSHOPTK';
            $bonus['tplmesg_info'] = json_encode($res);
            $CardUserUpdate = new CardUserUpdate();
            $CardUserGet = new CardUserGet();
            $CardUserUpdate->allowField(true)->save($bonus);
            $map['openid'] = $bonus['openid'];
            $map['card_id'] = $bonus['card_id'];
            $CardUserGet->where($map)->setField('bonus', $res['result_bonus']);
            return '0';
        }else{
            return "1";
        }
    }

    //商户ID
    public function getmid($arr){
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $mid = $CardMember->where(array('card_id'=>$arr))->value('mid');
        if (empty($mid)){
            $mid = $CardGeneral->where(array('card_id'=>$arr))->value('mid');
            return $mid;
        }else{
            return $mid;
        }
    }

    //积分核销
    public function updateuser($arr){
        $data['mid'] = $arr['mid'];
        $data['openid'] = $arr['openid'];
        $data['code'] = $arr['code'];
        $data['card_id'] = $arr['card_id'];
        $data['create_time'] = time();
        $data['outerid'] = 1;
        $data['add_bonus'] = $arr['add_bonus'];
        $CardUserUpdate = new CardUserUpdate();
        $CardUserUpdate->save($data);
        $bonus = abs($data['add_bonus']);
        $CardUserGet = new CardUserGet();
        $CardUserGet->where(array('code'=>$data['code'],'card_id'=>$data['card_id']))->setField('bonus',$bonus);
    }

    //微信API参数  根据card_id获取
    public function options($card_id = ''){
        $card_id = $this->get_cardus_id();
        Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System=new System();
        $WxOpen=new WxOpen();
        $Agent=new Agent();
        $mid = $CardMember->where('card_id',$card_id)->value('mid');
        if ($mid){
            $map['id'] = $mid;
        }else{
            $map['id'] = $CardGeneral->where('card_id',$card_id)->value('mid');
        }
        $merchantinfo=$Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $users = $WxOpen->where($mab)->find();
        $config=$Agent->where(array('id'=>$merchantinfo['agent']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //商品列表
    public function catelist($card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardGoodsCate = new CardGoodsCate();
        //搜素
        $request = request();
        $p_data = $request->get();
        $map['card_id'] = $card_id;
        $map['top_mid'] = Session::get('login_top_mid');
        $list = $CardGoodsCate->where($map)->order('id desc')->paginate('10', false, ['query' => request()->param()]);
        $card['card_id'] = $card_id;
        $this->assign('p_data',$p_data);
        $this->assign('card',$card);
        $this->assign('list', $list);
        return $this->fetch();
    }

    //商品详情
    public function cateinfo($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardGoodsCate = new CardGoodsCate();
        $info = $CardGoodsCate->where(array('id'=>$id))->find();
        $card['card_id'] = $card_id;
        $this->assign('card',$card);
        $this->assign('goods', $info);
        return $this->fetch();
    }

    //添加商品
    public function cateadd($card_id = ''){
        $card_id = $this->get_cardus_id();
        if (Request()->isPost()){
            $arr = request()->post();
            $data = $arr;
            $CardGoodsCate = new CardGoodsCate();
            $data['top_mid'] = Session::get('login_top_mid');
            $data['card_id'] = $card_id;
            $data['name'] = $arr['name'];
            $data['create_time'] = time();
            $res = $CardGoodsCate->allowField(true)->save($data);
            if ($res){
                $rarr['code'] = 0;
                $rarr['message'] = 'success';
                $rarr['url'] =url('shoptest/catelist',['card_id'=>$card_id]);
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = 'error';
                $rarr['url'] =url('shoptest/catelist',['card_id'=>$card_id]);
            }
            return json($rarr);
        }else{
            $card['card_id'] = $card_id;
            $this->assign('card',$card);
            return $this->fetch();
        }
    }

    //修改商品
    public function cateedit($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        if (Request()->isPost()){
            $arr = request()->post();
            $data['name'] = $arr['name'];
            $CardGoodsCate = new CardGoodsCate();
            $res = $CardGoodsCate->allowField(true)->save($data,['id'=>$id]);
            if ($res){
                $rarr['code'] = 0;
                $rarr['message'] = 'success';
                $rarr['url'] =url('shoptest/catelist',['card_id'=>$card_id]);

            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = 'error';
                $rarr['url'] =url('shoptest/catelist',['card_id'=>$card_id]);
            }
            return json($rarr);
        }else{
            $CardGoodsCate = new CardGoodsCate();
            $info = $CardGoodsCate->where(array('id'=>$id))->find();
            $card['card_id'] = $card_id;
            $this->assign('card',$card);
            $this->assign('info',$info);
            return $this->fetch();
        }
    }

    //删除商品
    public function catedel($id,$card_id = ''){
        $card_id = $this->get_cardus_id();
        $CardGoodsCate = new CardGoodsCate();
        $del = $CardGoodsCate->where(['id'=>$id])->delete();
        if ($del) {
            $this->success('删除成功',url('shoptest/catelist',['card_id'=>$card_id]));
        } else {
            $this->error('删除失败',url('shoptest/catelist',['card_id'=>$card_id]));
        }
    }

}
